package han.fetch;

import com.han.http.client.paramter.FormDataPair;
import com.han.http.client.paramter.RequestHeader;
import com.han.http.fetch.Fetcher;
import han.proof.Cookie;
import org.json.JSONObject;

import static com.han.http.util.Print.printlnErr;

/**
 * @author: Han
 * @date: 2018/9/14 13:56
 * @dscription: 登录鲸准APP, 获取cookie
 */
public class Login {

    static Cookie login(String username, String password) {
        password = password.replace("'", "%27");
        //请求头
        RequestHeader[] requestHeaders = {
                new RequestHeader("User-Agent", "36kr-Tou-Android/5.0.3 (MI 6; Android 8.0.0; Scale/1920x1080)"),
                new RequestHeader("Content-Type", "application/x-www-form-urlencoded"),
                new RequestHeader("Content-Length", "50"),
                new RequestHeader("Host", "rong.36kr.com"),
                new RequestHeader("Connection", "Keep-Alive"),
                new RequestHeader("Accept-Encoding", "gzip"),
        };
        //post data
        FormDataPair[] formDataPairs = {
                new FormDataPair("type", "PHONE"),
                new FormDataPair("phone", username),
                new FormDataPair("password", password),
        };
        String url = "https://rong.36kr.com/api/passport/v1/ulogin";
        int generalTimeout = 1000 * 10;
        Fetcher fetcher = new Fetcher();
        Cookie cookie = null;
        String json = "";
        try {
            //获取返回值
            json = fetcher.getPageInfoByPost(url, requestHeaders, formDataPairs, generalTimeout,
                    generalTimeout, false, "utf8", null);
            //解析json数据
            JSONObject dataObj = new JSONObject(json).getJSONObject("data");
            long id = dataObj.getLong("kr_plus_id");
            String token = dataObj.getString("kr_plus_token");
            long version = dataObj.getLong("krid_user_version");
            //拼接cookie
            String cookieStr = "kr_plus_id=" + id + ";kr_plus_token=" + token + ";krid_user_version=" + version;
            cookie = new Cookie(username, cookieStr);
        } catch (Exception e) {
            printlnErr(username + ",解析失败:" + json);
            e.printStackTrace();
        }
        return cookie;
    }
}
